package kr.saeildamil.androidstudy_second25;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class SDCard extends Activity {
	EditText mEdit;
	String mSdPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_sdcard);

		mEdit=(EditText) findViewById(R.id.edittext);

		String ext=Environment.getExternalStorageState();
		

		if(ext.equals(Environment.MEDIA_MOUNTED)){
			mSdPath=Environment.getExternalStorageDirectory().getAbsolutePath();
			prnStat(mSdPath);
		}else{
			mSdPath=Environment.MEDIA_UNMOUNTED;
		}
	}
	
	public void mOnClick(View v){
		switch (v.getId()) {
		case R.id.test:
			String rootdir=Environment.getRootDirectory().getAbsolutePath();
			String datadir=Environment.getDataDirectory().getAbsolutePath();
			String cachedir=Environment.getDownloadCacheDirectory().getAbsolutePath();
			String text=String.format("ext=%s\nroot=%s\ndata=%s\ncache=%s", mSdPath,rootdir,datadir,cachedir);
			mEdit.setText(text);
			break;

		case R.id.save:
			File dir=new File(mSdPath+"/dir");
			dir.mkdir();
			File file=new File(mSdPath+"/dir/fileio.txt");
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
				String str="This file exists in SDCard";
				fos.write(str.getBytes());
				fos.close();
				mEdit.setText("Write Success");
			} catch (FileNotFoundException e) {
				mEdit.setText("File Not Found");
			} catch (IOException e) {
				mEdit.setText(e.getMessage());
			} catch (SecurityException e) {
				mEdit.setText("SecurityException");
			}
			break;
			
		case R.id.load:
			FileInputStream fis;
			try {
				fis=new FileInputStream(mSdPath+"/dir/fileio.txt");
				byte[] data=new byte[fis.available()];
				fis.read(data);
				mEdit.setText(new String(data));
				fis.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	private void prnStat(String str) {
		Toast.makeText(this, str, Toast.LENGTH_SHORT);
	}

}

